/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.job.snailjob;

import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.isfd.domain.bo.IsfdDatasourceTaskSchedulingConfigActionBo;
import com.comac.ins.isfd.domain.vo.IsfdDatasourceTaskSchedulingConfigVo;
import com.comac.ins.isfd.service.IIsfdDatasourceTaskSchedulingConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 数据源数据集成任务调度执行器
 */
@Slf4j
@Component
@JobExecutor(name = "isfdDataSourceTaskJobExecutor")
public class IsfdDataSourceTaskJobExecutor {
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private IIsfdDatasourceTaskSchedulingConfigService iIsfdDatasourceTaskSchedulingConfigService;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        Date nowTime = new Date();
        List<IsfdDatasourceTaskSchedulingConfigVo> taskSchedulingConfigVoList = iIsfdDatasourceTaskSchedulingConfigService.scanBeforeNowTimeList(nowTime);
        if (CollectionUtils.isEmpty(taskSchedulingConfigVoList)) {
            return ExecuteResult.success("数据源数据集成，未扫描到数据，任务调度执行完成！");
        }
        //一个线程一个任务
        for (IsfdDatasourceTaskSchedulingConfigVo taskSchedulingConfigVo : taskSchedulingConfigVoList) {
            threadPoolTaskExecutor.execute(() -> {
                try {
                    IsfdDatasourceTaskSchedulingConfigActionBo actionBo = new IsfdDatasourceTaskSchedulingConfigActionBo();
                    actionBo.setTaskId(taskSchedulingConfigVo.getTaskId());
                    iIsfdDatasourceTaskSchedulingConfigService.trigger(actionBo);
                } catch (Exception e) {
                    log.info("data source task job is trigger is fail,task config is {}", JsonUtils.toJsonString(taskSchedulingConfigVo));
                    log.error("data source task job is trigger is fail", e);
                }
            });
        }
        return ExecuteResult.success("数据源数据集成，任务调度执行完成！");
    }
}
